/*
 * @Title: community
 * @Description: TODO
 * @author MI
 * @date 2022/7/25 10:16
 * @version
 */
package com.shanshan.community.controller.interceptor;

import com.jhlabs.vecmath.Tuple3f;
import com.shanshan.community.entity.LoginTicket;
import com.shanshan.community.entity.User;
import com.shanshan.community.service.UserService;
import com.shanshan.community.util.CookieUtil;
import com.shanshan.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.TypeVariable;
import java.util.Date;

/**
 * @author MI
 * @ClassName: LoginTicketInterceptor
 * @Description: 登录凭证拦截器
 * @date 2022/7/25 10:16
 */

@Component
public class LoginTicketInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private HostHolder hostHolder;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie
        String ticket = CookieUtil.getValue(request, "ticket");
        if (ticket != null) {
            //查询凭证
            LoginTicket loginTicket = userService.findLoginTicket(ticket);
            //检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                User user = userService.findUserById(loginTicket.getUserId());
                //存入到thread local中去
                hostHolder.setUser(user);
            }
        }
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //获取thread local里面的user
        User user = hostHolder.getUser();
        if (user != null && modelAndView != null) {
            modelAndView.addObject("loginUser", user);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清除用户数据
        hostHolder.clear();
    }
}
